<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}用户`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="真实姓名" prop="realName">
        <el-input v-model="drawerProps.row.realName" placeholder="请填写真实姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="是否管理员" prop="adminFlag">
        <el-switch
          :disabled="!userStore.userInfo.adminFlag"
          :active-value="1"
          :inactive-value="0"
          v-model="drawerProps.row.adminFlag"
        />
      </el-form-item>
      <el-form-item label="账号" prop="username">
        <el-input v-model="drawerProps.row.username" placeholder="请填写账号" clearable></el-input>
      </el-form-item>

      <el-form-item v-show="!drawerProps.isView" label="密码" prop="password">
        <el-input v-model="drawerProps.row.password" placeholder="请填写密码" clearable></el-input>
      </el-form-item>
      <el-form-item label="部门" prop="department">
        <el-input v-model="drawerProps.row.department" placeholder="请填写部门" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Admin } from "@/api/interface";
import { useUserStore } from "@/stores/modules/user";
const userStore = useUserStore();
const rules = reactive({
  username: [{ required: true, message: "请填写账号" }],
  password: [{ required: true, message: "请填写密码" }],
  department: [{ required: true, message: "请选择部门" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Admin>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
